package com.vcredit.creditcat.manager.product;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.config.annotation.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.api.ICrfManager;
import com.vcredit.creditcat.dto.product.CreditCRFAmountParamDto;
import com.vcredit.creditcat.enumtype.ApiEnum;
import com.vcredit.creditcat.enumtype.CRFAuditResultEnum;
import com.vcredit.creditcat.enumtype.MerchantProductEnum;
import com.vcredit.creditcat.enumtype.SmsDescEnum;
import com.vcredit.creditcat.exception.DataException;
import com.vcredit.creditcat.manager.SMSMessageManager;
import com.vcredit.creditcat.model.CustAccount;
import com.vcredit.creditcat.model.CustProductApply;
import com.vcredit.creditcat.service.CustAccountService;
import com.vcredit.creditcat.service.CustProductApplyService;
import com.vcredit.creditcat.service.CustService;
import com.vcredit.creditcat.service.income.MyIncomeService;
import com.vcredit.creditcat.service.product.CreditCommonApplyService;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.creditcat.util.Encrypt;
import com.vcredit.creditcat.util.EnumExtUtil;
import com.vcredit.creditcat.util.JsonUtil;
import com.vcredit.creditcat.util.RSAUtil;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.JacksonUtil;

@Service(protocol = { "protocol1" }, version = "1.0")
public class CrfProductManager implements ICrfManager {

	@Value("${crf.xinyongmao.dataSource}")
	private String dataSource;

	@Value("${crf.xinyongmao.key}")
	private String key;

	@Autowired
	private MyIncomeService myIncomeService;
	@Autowired
	private CustProductApplyService custProductApplyService;
	@Autowired
	private CustService custService;
	@Autowired
	private ProductApplyManager productApplyManager;

	@Autowired
	public CreditCommonApplyService creditCommonApplyService;
	
	@Autowired
	private CustAccountService custAccountService;
	
	@Autowired
	public SMSMessageManager sMSMessageManager;


	private final String orderIdPram = "XYM_";
	private final String paramErr = "验签错误!";

	public String encodeJsonParampri(String jsonParam) throws UnsupportedEncodingException, Exception {
		// 加密
		String requestContentBase64 = Base64
				.encodeBase64String(RSAUtil.encryptByPrivateKey(jsonParam.getBytes("utf-8"), "privateKey"));
		return requestContentBase64;
	}

	/**
	 * String result = ""; // 解密 byte[] res = RSAUtil.decryptBASE64(respJson);
	 * result = new String(RSAUtil.decryptByPublicKey(res, this.publicKey));
	 * return result;
	 */
	@Log
	@Override
	public String decodeJsonParampub(String signature, String datasou, CreditCRFAmountParamDto jsonParam)
			throws DataException, Exception {
		String xign = JsonUtil.obj2Json(jsonParam, true);

		String jsonSignatue = Encrypt.base64HmacMD5(this.key, xign);

		if ("".equals(jsonParam) && jsonParam == null) {
			throw new DataException(paramErr);
		}

		if (!jsonSignatue.contains(signature)) {
			throw new DataException(paramErr);
		}
		return xign;
	}

	@Log
	@Override
	public void dealResult(String productName, String jsonParam) throws Exception {
		// TODO Auto-generated method stub
		productApplyManager.noticeApplyResult(this.productApply(productName, jsonParam.toString()), productName);
	}

	/**
	 * 所需参数封装
	 * 
	 * @param productName
	 * @param jsonParam
	 * @return
	 * @throws Exception
	 */
	public CustProductApply productApply(String productName, String jsonParam) throws Exception {
		ApiEnum enumOnValue = EnumExtUtil.getEnumOnValue(ApiEnum.class, productName, "key");

		CustProductApply cust = new CustProductApply();
		switch (enumOnValue) {
		case crfProduct:
			// 信而富相关返回处理 结果拼装
			cust = this.param(jsonParam);
			break;		
		}
		return cust;
	}

	
	/**
	 * 信而富 参数处理
	 * 
	 * @param jsonEntry
	 * @return
	 * @throws Exception
	 */
	public CustProductApply param(String jsonEntry) throws Exception {
		CreditCRFAmountParamDto result = JacksonUtil.Json2Obj(jsonEntry, new TypeReference<CreditCRFAmountParamDto>() {
		});
		long custId = Long.valueOf(result.getOrderId().replace(orderIdPram, ""));
		CustProductApply custold =custProductApplyService.findNewApplyProduct((long)MerchantProductEnum.creditCRF.getCode(), custId);
		CustProductApply cust = new CustProductApply();
		if(null!=custold.getIsApply()){
			cust.setApplyId(custold.getApplyId());
		}
		cust.setCustId(custId);
		cust.setProductId(new Long(25));
		cust.setIsApply(false);

		
		List<CustProductApply> list = custProductApplyService.findByConditions(cust);
		if (list.size() > 0) {
			cust.setApplyId(list.get(0).getApplyId());
		}
		String flowNo = Utility.nextCode(MerchantProductEnum.creditCRF.name().toUpperCase());
		cust.setFlowNo(flowNo);
		CRFAuditResultEnum enumOnValue = EnumExtUtil.getEnumOnValue(CRFAuditResultEnum.class, result.getOrderState(),
				"key");

		switch (enumOnValue) {
		// 审核结果 0：已审批-失败；1：已审批-成功；2：审批中；3：未申请过；4：未申请过，认证条件齐全 5过渡条件
		case noneOrder:
			cust.setAuditResult(3);
			break;
		case notpassOrder:
			cust.setAuditResult(0);
			cust.setIsApply(true);
			cust.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));
			
			try {  //发送失败短信，不影响主流程
				CustAccount account = new CustAccount();
				account.setCustId(cust.getCustId());
				
				CustAccount  custAccount=custAccountService.find(account).get(0);
				
				String mobile = custAccount.getUserName();				
				String appdesc=custAccount.getAppDesc();				
				appdesc=appdesc.split(";")[0].toString();			
				String productName=SmsDescEnum.getNameByAppDesc(appdesc);
				String userName=custAccount.getAccountRealname();

				
				sMSMessageManager.sendCreditFail(mobile,productName,userName);
			} catch (Exception e) {
				
			}
			
			break;
		case applingOrder:
			cust.setAuditResult(2);
			break;
		case throughOrder:
			//myIncomeService.addIncome(custId, 1);  //信而富特殊情况,流水是反馈,申请成功不算成功
			cust.setCreditExpiretime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));
			cust.setAuditResult(1);
			
			try { //发送成功短信，不影响主流程
				CustAccount account = new CustAccount();
				account.setCustId(cust.getCustId());
				CustAccount  custAccount=custAccountService.find(account).get(0);
				
				String mobile = custAccount.getUserName();				
				String appdesc=custAccount.getAppDesc();	
				String key=appdesc.split(";")[0].toString();
				appdesc=appdesc.split(";")[0].toString();			
				String productName=SmsDescEnum.getNameByAppDesc(appdesc);
				String userName=custAccount.getAccountRealname();
				
				
				sMSMessageManager.sendCreditSuccess(mobile,productName,userName);
			} catch (Exception e) {
				
			}
			break;
		default:
			break;
		}
		cust.setRejectMsg(enumOnValue.getDesc());
		cust.setCustId(custId);
		cust.setAuditTime(ConcurrentDateUtil.formatDateTime(new Date()));
		return cust;
	}
}
